import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
// import { getToken } from '@/utils/auth' // get token from cookie
// import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/static'] // no redirect whitelist


router.beforeEach( async (to, from, next) => {
  console.log("before each..")

  // start progress bar
  NProgress.start()
  if (to.meta.title !== undefined) {
    document.title = to.meta.title
  } else {
    document.title = '\u200E'
  }
  // store.commit('router/initRoutes')
  // store.commit('initRoutes')
  console.log("before each1..")

  if (to.path) {
    // eslint-disable-next-line no-undef
    _hmt.push(['_trackPageview', '/#' + to.fullPath])
  }
  console.log("before each12..")
  // next()
  if (store.getters.userInfo) { // 如果存在用户信息说明已经登录
    if (to.path === '/login') {
      console.log("before each3..", to.path)
      next({path: '/'});
      NProgress.done()
    } else {
      if (store.getters.userRoles && store.getters.userRoles.length > 0) {
        console.log("before each5..")
        next()   //当有用户权限的时候，说明所有可访问路由已生成 如访问没权限的全面会自动进入404页面
      } else {
        try {
          let roleIndex = 3;
          try {
            roleIndex = JSON.parse(JSON.stringify(decodeURIComponent(store.getters.userInfo)))['role']

          } catch (err) {
            console.log(err)
            roleIndex = 3
          }
          let roles = null;
          if (roleIndex === 3) {
            roles = ['admin']
          } else if (roleIndex === 2) {
            roles = ['teacher']
          } else {
            roles = ['student']
          }
          console.log(roles, "roles")


          store.commit("user/setUserRoles", roles)
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles);
          // store.enumFormat(roles)
          router.addRoutes(accessRoutes)  // 动态添加可访问的路由
          next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
        } catch (error) {
          console.log("error", error)
          await store.commit('user/clearRoles')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      console.log('white...')
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      console.log("redirect")
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
